<?php
$packageName = $argv[1];
$repoID = $argv[2];

mkdir($packageName);

$yamlTemp = <<<EOF
version_control: github
src_repo: {$repoID}
tag_prefix: ^
seperator: .
EOF;

file_put_contents($packageName.'/'.$packageName.".yaml", $yamlTemp);

$infoapiurl = "https://api.github.com/repos/{$repoID}";
$info = json_decode(httpget($infoapiurl), true);
$commiturl = "https://api.github.com/repos/{$repoID}/commits";
$commits = json_decode(httpget($commiturl), true);
$reponame = explode('/', $repoID)[1];
$lcommit = $commits[0]['sha'];
$license = strtoupper($info['license']['key']);
$description = $info['description'];

$specTemp = <<<EOF
%global goreponame      {$reponame}
%global goipath         github.com/{$repoID}
%global commit          {$lcommit}

%gometa

%global common_description {$description}

%global golicenses      LICENSE
%global godocs          README.md

Name:           %{goname}
Version:        0
Release:        1
Summary:        %{common_description}

License:        {$license}
URL:            https://%{goipath}
Source0:        https://%{goipath}/archive/%{commit}/%{goreponame}-%{commit}.tar.gz

%description
%{common_description}

%package devel
Summary:       %{common_description}
BuildArch:     noarch

%description devel
This package contains library source intended for building other packages,
which use import path with %{common_description} prefix.

%prep
%setup -n %{goreponame}-%{commit}

%install
mkdir -p %{buildroot}%{gopath}/src/%{goipath}
cp -r ./* %{buildroot}%{gopath}/src/%{goipath}
chmod 755 %{buildroot}%{gopath}/src/%{goipath}/*
%files devel
%doc %{golicenses} %{godocs}
%{gopath}/src/%{goipath}

%changelog
* Sat Aug 28 2021 bzp2010 <1286886774@qq.com> - 0-1
- Initial package

EOF;

file_put_contents($packageName.'/'.$packageName.".spec", $specTemp);

echo "https://github.com/{$repoID}/archive/{$lcommit}/{$reponame}-{$lcommit}.tar.gz\n";
echo "[{$packageName}: https://gitee.com/bzp2010/{$packageName}](https://gitee.com/bzp2010/{$packageName})";

function httpget($url) {
	$curl = curl_init();

	curl_setopt_array($curl, array(
	  CURLOPT_URL => $url,
	  CURLOPT_RETURNTRANSFER => true,
	  CURLOPT_ENCODING => '',
	  CURLOPT_MAXREDIRS => 10,
	  CURLOPT_TIMEOUT => 0,
	  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	  CURLOPT_CUSTOMREQUEST => 'GET',
	  //CURLOPT_PROXY => '127.0.0.1:8888',
	  CURLOPT_SSL_VERIFYHOST => false,
	  CURLOPT_SSL_VERIFYPEER => false,
	  CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.78",
	));

	$response = curl_exec($curl);

	curl_close($curl);

	return $response;
}